package com.faner.fast.email.service.impl;

import cn.hutool.extra.mail.Mail;
import cn.hutool.extra.mail.MailAccount;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.faner.fast.email.mapper.EmailConfigMapper;
import com.faner.fast.email.pojo.model.EmailConfigDO;
import com.faner.fast.email.pojo.vo.EmailDTO;
import com.faner.fast.email.service.EmailConfigService;
import com.faner.fast.exception.FailedException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * description: EmailConfigServiceImpl
 * date: 2020/11/26 11:22
 * author: faner
 */
@Service
public class EmailConfigServiceImpl extends ServiceImpl<EmailConfigMapper, EmailConfigDO> implements EmailConfigService {


    @Override
    public EmailConfigDO find() {
        EmailConfigDO emailConfig = this.baseMapper.selectById(3L);
        Optional<EmailConfigDO> emailConfig1 = Optional.ofNullable(emailConfig);
        return emailConfig1.orElseGet(EmailConfigDO::new);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void send(EmailDTO emailDTO, EmailConfigDO emailConfig) {
        if(emailConfig.getId() == null){
            throw new FailedException("请先配置，再操作");
        }
        // 封装
        MailAccount account = new MailAccount();
        account.setUser(emailConfig.getUser());
        account.setHost(emailConfig.getHost());
        account.setPort(Integer.parseInt(emailConfig.getPort()));
        account.setAuth(true);
        try {
            // 对称解密
//            account.setPass(EncryptUtil.desDecrypt(emailConfig.getPass()));
            account.setPass(emailConfig.getPass());
        } catch (Exception e) {
            throw new FailedException(e.getMessage());
        }
        account.setFrom(emailConfig.getUser()+"<"+emailConfig.getFromUser()+">");
        // ssl方式发送
        account.setSslEnable(true);
        // 使用STARTTLS安全连接
        account.setStarttlsEnable(true);
//        MailUtil.send(account, CollUtil.newArrayList(StrUtil.join(",",emailDTO.getTos())), emailDTO.getSubject(), emailDTO.getContent(), false, null);
        String content = emailDTO.getContent();
//        File f = new File( "http://hawk-att.oss-cn-beijing.aliyuncs.com/clinic/images/2020/11/25/16062972200406465.jpg");
        // 发送
        try {
            int size = emailDTO.getTos().size();
            Mail.create(account)
                    .setTos(emailDTO.getTos().toArray(new String[size]))
                    .setTitle(emailDTO.getSubject())
                    .setContent(content)
                    .setHtml(true)
//                    .setFiles(f)
                    //关闭session
                    .setUseGlobalSession(false)
                    .send();
        }catch (Exception e){
            throw new FailedException(e.getMessage());
        }

    }
}
